<template>
	<eui-button :modelValue="scope" title="缺货登记" singleTag="stockout" class="margin"
		v-show="scope.orderStatus === '2' && scope.isPrinted === '1'" @buttonClick="buttonClick" type="max2" />
	<Popover :contents="[{
		text: '部分退款',
		showBtn: scope.refundOperateType?.includes('1'),
		value: scope
	}, {
		text: '重量退差',
		showBtn: scope.refundOperateType?.includes('2'),
		value: scope
	}, {
		text: '金额退差',
		showBtn: scope.refundOperateType?.includes('3'),
		value: scope
	}, {
		text: '取消订单',
		showBtn: scope.refundOperateType?.includes('0'),
		value: scope
	}]" theme="dark" placement="top" @select="onSelect" width="167" v-show="!!scope?.refundOperateType">
		<template v-slot:reference>
			<view
				v-show="(!!scope?.refundOperateType && (scope?.refundOperateType?.includes('2') || scope?.refundOperateType?.includes('3')) || (scope?.refundOperateType?.includes('1')) || (scope?.refundOperateType?.includes('0')))"
				style="height: 66rpx;line-height: 66rpx;border-radius: 40rpx;text-align: center;border: 1rpx solid rgb(136, 136, 136);width: 180rpx;font-size: 28rpx;color:rgb(51, 51, 51) !important;">
				退款</view>
		</template>
	</Popover>
	<eui-button :modelValue="scope" title="拒单" singleTag="delete" type="max2" v-show="scope.orderStatus === '1'"
		class="margin" @buttonClick="buttonClick" />
	<eui-button :modelValue="scope" title="接单并打印" singleTag="confrim" v-show="scope.orderStatus === '1'" class="margin"
		@buttonClick="buttonClick" type="max" />
	<eui-button :modelValue="scope" title="打印" singleTag="print" type="max" class="margin"
		v-show="scope.orderStatus === '2' && scope.isPrinted === '0'" @buttonClick="buttonClick" />
	<eui-button :modelValue="scope" title="拣货" singleTag="picking" type="max" class="margin"
		v-show="scope.orderStatus === '2' && scope.isPrinted === '1'" @buttonClick="buttonClick" />
	<eui-button :modelValue="scope" title="取消配送" singleTag="delivery" type="max2" class="margin"
		v-show="scope.orderStatus === '3' || scope.orderStatus === '4'" @buttonClick="buttonClick" />
	<eui-button :modelValue="scope" title="催骑手接单" singleTag="push" type="max" class="margin"
		v-show="scope.orderStatus === '3' && scope.deliveryStatus === '6' && scope.deliveryType === '1' && (scope.chnlType === 'jddj' || scope.chnlType === 'meituan')"
		@buttonClick="buttonClick" />
	<eui-button :modelValue="scope" title="转自配送" singleTag="send" type="max" class="margin"
		v-show="scope.orderStatus === '3' && ((scope.chnlType === 'eleme' && scope.changeDeliveryStatus === '1') || (scope.chnlType === 'meituan' && formatPickTime(scope.pickupTime) > 15) || (scope.chnlType === 'jddj' && formatPickTime(scope.pickupTime) > 10)) && scope.deliveryType === '1'"
		@buttonClick="buttonClick" />
	<eui-button :modelValue="scope" title="发货" singleTag="confirmDelivery" type="max" class="margin"
		v-show="scope.orderStatus === '25' || (scope.orderStatus === '9' && scope.lockStatus === '0')"
		@buttonClick="buttonClick" />
	<eui-button :modelValue="scope" title="确认出库" singleTag="submit" type="max" class="margin"
		v-show="scope.orderStatus === '3'" @buttonClick="buttonClick" />
	<eui-button :modelValue="scope" title="转自配送" singleTag="send" type="max" class="margin"
		v-show="scope.orderStatus === '4' && scope.deliveryType === '1' && ((scope.chnlType === 'eleme' && scope.changeDeliveryStatus === '1') || (scope.chnlType === 'meituan' && formatPickTime(scope.pickupTime) > 15) || (scope.chnlType === 'jddj' && formatPickTime(scope.pickupTime) > 10)) && scope.deliveryStatus !== '13'" />
	<eui-button :modelValue="scope" title="确认拒收" singleTag="red" type="max2" @buttonClick="buttonClick" class="margin"
		v-show="scope.orderStatus === '4' && ((scope.chnlType === 'jddj' && scope.lockStatus === '1') || (scope.chnlType === 'eleme' && scope.deliveryStatus === '19'))" />
	<eui-button :modelValue="scope" title="妥投成功" singleTag="submit2" type="max" @buttonClick="buttonClick"
		class="margin" v-show="scope.orderStatus === '4' && scope.deliveryType === '2' && scope.deliveryStatus !== '13'" />
	<eui-button :modelValue="scope" title="确认提货" singleTag="submit3" type="max" @buttonClick="buttonClick"
		class="margin" v-show="scope.orderStatus === '5' && scope.deliveryStatus !== '100'" />
	<eui-button :modelValue="scope" title="驳回申请" singleTag="red2" type="max2" @buttonClick="buttonClick" class="margin"
		v-show="scope.afsOrderStatus === '10'" />
	<eui-button :modelValue="scope" title="审核通过" singleTag="submit5" type="max" @buttonClick="buttonClick"
		class="margin" v-show="scope.afsOrderStatus === '10' && scope.allowChangeType === '1'" />
	<eui-button :modelValue="scope" title="审核通过" singleTag="submit4" type="max" @buttonClick="buttonClick"
		class="margin" v-show="scope.afsOrderStatus === '10' && scope.allowChangeType === '0'" />
	<eui-button :modelValue="scope" title="退货发配送" singleTag="red3" type="max2" @buttonClick="buttonClick" class="margin"
		v-show="(((scope.afsOrderStatus === '12' && ['1', '12'].includes(scope.deliveryStatus)) && scope.refundGoodsDeliveryType !== '2' && !!scope.refundGoodsDeliveryType))" />
	<eui-button :modelValue="scope" title="取消退货配送" singleTag="red4" type="max2" @buttonClick="buttonClick"
		class="margin"
		v-show="(((scope.afsOrderStatus === '12' && !['1', '12'].includes(scope.deliveryStatus)) && scope.refundGoodsDeliveryType !== '2' && !!scope.refundGoodsDeliveryType))" />
	<eui-button :modelValue="scope" title="驳回入库申请" singleTag="red2" type="max2" @buttonClick="buttonClick"
		class="margin"
		v-show="(((scope.afsOrderStatus === '12' || scope.afsOrderStatus === '17') && scope.refundGoodsDeliveryType !== '2' && !!scope.refundGoodsDeliveryType) || (scope.afsOrderStatus === '17' && scope.refundGoodsDeliveryType === '2'))" />
	<eui-button :modelValue="scope" title="确认入库" singleTag="submit6" type="max" @buttonClick="buttonClick"
		class="margin"
		v-show="(((scope.afsOrderStatus === '12' && !scope.deliveryStatus) && scope.refundGoodsDeliveryType !== '2' && !!scope.refundGoodsDeliveryType) || (scope.afsOrderStatus === '17' && !!scope.refundGoodsDeliveryType))" />
</template>
<script setup lang="ts">
import { formatPickTime } from '../../../../hooks/useDatetimeUtil';
import { getBcmDictList } from '../../../../hooks/bcmUseUntils';
import service from '@/common/service';
import { getBcmUrl, bcmRequest } from '../../../../hooks/bcmServices';
import Popover from '../../components/Popover.vue'

const bcmUrl = getBcmUrl()
const props = defineProps<{
	scope?: any;
	orderItem?: any;
	currentItem?: any;
	modalType?: any;
	title?: any;
	modelValue?: any;
	showOrderPickupPop?: boolean;
	showCancelOrderPopup?: boolean;
	isOrderCancel?: boolean;
	showDeliveryCancelPopup?: boolean;
	dealType?: any;
	dealList?: any;
	showConfirmApplyOrderPopup?: boolean;
	showAuditSendAfsPopup?: boolean;
	showConfigModal?:boolean;
}>()

const { scope, showConfigModal } = props;

const emit = defineEmits(['buttonClick', 'close', 'fetchData', 'gdsPopupOpen', 'update:modelValue', 'update:currentItem', 'update:modalType', 'update:title', 'update:isOrderCancel', 'update:showCancelOrderPopup', 'update:showDeliveryCancelPopup', 'update:dealType', 'update:dealList', 'update:showConfirmApplyOrderPopup', 'update:showOrderPickupPop', 'update:showAuditSendAfsPopup', 'orderItemPrint', 'update:billType'])

const orderAction = async function (a: {
	uniqueKey: string,
	methodName: string
}, v: any, params: any = undefined, text = '', popup = false, fn: any = undefined) {
	service.enjoyShowLoading('正在加载...');
	let param = {
		chnlCode: v.chnlCode,
		chnlType: v.chnlType,
		orderNo: v.orderNo,
		storeCode: v.storeCode,
		thirdOrderNo: v.thirdOrderNo,
		orderId: v.orderId,
		...params,
	}
	const response = await bcmRequest(bcmUrl.orderApi, a.uniqueKey, a.methodName, param);
	service.enjoyHideLoading();
	if (text) {
		uni.showToast({
			title: text,
			icon: 'none'
		});
	}
	if (popup) {
		close()
	}
	emit('fetchData')
	if (fn) {
		fn(v)
	}
	if (params) {
		return response
	}
}

const buttonClick = (t: any) => {
	const { singleTag, modelValue } = t;
	let v = modelValue;
	switch (singleTag) {
		case 'confirmDelivery':
			uni.navigateTo({
				url: `/pages/BcmViews/PickingOrder/confirmDelivery?orderItem=${encodeURIComponent(JSON.stringify({
					orderId: v.orderId,
					consigneeName: v.consigneeName,
					consigneePhone: v.consigneePhone,
					consigneePhoneLast: v.consigneePhoneLast,
					consigneeAddress: v.consigneeAddress
				}))}`,
			});
			break;
		case 'red3':
			uni.navigateTo({
				url: `/pages/BcmViews/PickingOrder/confirmAfsDelivery?orderItem=${encodeURIComponent(JSON.stringify({
					afsOrderId: v.afsOrderId,
					consigneeName: v.contactName,
					consigneePhone: v.privacyContactPhone || v.contactPhone,
					consigneePhoneLast: v.consigneePhoneLast,
					consigneeAddress: v.pickUpAddress,
					expectPickUpStartTime: v.expectPickUpStartTime,
					expectPickUpEndTime: v.expectPickUpEndTime
				}))}`,
			});
			break;
		case 'red4':
			emit('update:modelValue', v)
			emit('update:billType', '2')
			emit('update:showDeliveryCancelPopup', true)
			
			break;
		case 'stockout':
			uni.setStorageSync('orderItemStockout', JSON.stringify({
				goodsList: v.bcmOrderGoodsList,
				storeCode: v.storeCode
			}));
			uni.navigateTo({
				url: `/pages/BcmViews/PickingOrder/stockout`,
			});
			break;
		case 'delete':
			emit('update:modelValue', v)
			emit('update:modalType', v.orderStatus === '6' ? 'rejectOrderCancelApply' : 'cancel')
			emit('update:title', v.orderStatus === '6' ? '请选择拒绝退款申请原因' : '请选择取消订单原因')
			emit('update:isOrderCancel', false)
			emit('update:showCancelOrderPopup', true)
			break;
		case 'red2':
			emit('update:modelValue', v)
			emit('update:modalType', 'reject')
			emit('update:title', v.afsOrderStatus === '10' ? '请选择驳回售后申请原因' : '请选择驳回入库申请原因')
			emit('update:dealType', v.afsOrderStatus === '10' ? v.dealType : '3')
			let dealType = v.afsOrderStatus === '10' ? v.dealType : '3';
			emit('update:dealList', getBcmDictList('rejectReasonType').filter((a: any) => a.pdict.indexOf(dealType) != -
				1))
			emit('update:showCancelOrderPopup', true)
			break;
		case 'picking':
			let item = v;
			item.bcmOrderGoodsList.map((a: any) => {
				a.pickQuantity = (Number(a.goodsNum) - Number((!!a.refundGoodsNum ? a.refundGoodsNum :
					0))).toFixed(3);
				return a
			})
			emit('update:currentItem', item)
			emit('update:modelValue', item)
			emit('update:showOrderPickupPop', true)
			break;
		case 'confrim':
			orderAction({
				uniqueKey: '订单表',
				methodName: 'manualAcceptOrder'
			}, v, undefined, '接单成功', false, () => {
				emit('orderItemPrint', v)
			})
			break;
		case 'print':
			emit('orderItemPrint', v)
			break;
		case 'submit3':
			uni.showModal({
				title: '确认提货',
				content: '请确认，将订单号[' + v.thirdOrderNo + ']货物交给顾客吗?',
				showCancel: true,
				success: (res) => {
					if (res.confirm) {
						orderAction({
							uniqueKey: '订单表',
							methodName: 'confirmPickUpOrder'
						}, v, undefined, '确认提货操作成功');
					} else { }
				}
			});
			break;
		case 'submit':
			orderAction({
				uniqueKey: '订单表',
				methodName: 'confirmOutBoundOrder'
			}, v, undefined, '确认出库操作成功')
			break;
		case 'submit2':
			orderAction({
				uniqueKey: '订单表',
				methodName: 'deliveryEndOrder'
			}, v, undefined, '订单妥投操作成功')
			break;
		case 'submit4':
			confirmAcceptApplyOrder(v, v.dealType, true)
			break;
		case 'submit5':
			emit('update:modelValue', v)
			emit('update:showConfirmApplyOrderPopup', true)
			break;
		case 'red':
			uni.showModal({
				title: '确认拒收',
				content: '此操作将取消订单，您确定收到了顾客拒收退回来的商品吗？',
				showCancel: true,
				success: (res) => {
					if (res.confirm) {
						orderAction({
							uniqueKey: '订单表',
							methodName: 'confirmRejected'
						}, v, undefined, '拒收成功操作成功');
					} else { }
				}
			});
			break;
		case 'push':
			uni.showModal({
				title: '催骑手接单',
				content: '您确定要催骑手接单吗？',
				showCancel: true,
				success: (res) => {
					if (res.confirm) {
						orderAction({
							uniqueKey: '订单表',
							methodName: 'urgeDispatching'
						}, v, undefined, '操作成功');
					} else { }
				}
			});
			break;
		case 'send':
			uni.showModal({
				title: '转自配送',
				content: '您确定需要转自配送吗？',
				showCancel: true,
				success: (res) => {
					if (res.confirm) {
						orderAction({
							uniqueKey: '订单表',
							methodName: 'transformSelfDelivery'
						}, v, undefined, '订单转自配送操作成功');
					} else { }
				}
			});
			break;
		case 'submit6':
			if (v.afsOrderStatus === '12' && v.refundGoodsDeliveryType === '4') {
				uni.showToast({
					icon: 'none',
					title: '请联系买家发货后再执行此操作!'
				})
			} else {
				orderAction({
					uniqueKey: '售后单表',
					methodName: 'afsConfirmInBound'
				}, v, {
					afsOrderId: v.afsOrderId
				}, '确认入库操作成功').then((res) => {
					console.log(res, 'res')
					if (!['2', '1'].includes(v.syncErpBreakageStatus) && showConfigModal){
						uni.navigateTo({
							url: `/pages/BcmViews/PickingOrder/breakage?afsOrderId=` + v.afsOrderId + '&type=2'
						});
					}
				});
			}
			break;
		case 'delivery':
			emit('update:modelValue', v)
			emit('update:billType', '1')
			emit('update:showDeliveryCancelPopup', true)
			break;
	}

}

const confirmAcceptApplyOrder = function (v: any, dealType: any, showModal = false) {
	let text = '';
	if (v.returnGoodsType === '2' && v.isRefundAll === '0') {
		text = "部分退款订单将继续履约，您确定要退款给顾客吗？"
	}
	if (v.returnGoodsType === '1' || (v.returnGoodsType === '2' && v.isRefundAll === '1')) {
		text = "此操作将取消订单，您确定要退款给顾客吗？"
	}

	if (showModal) {
		uni.showModal({
			title: '提示',
			content: text,
			showCancel: true,
			success: (res) => {
				if (res.confirm) {
					orderAction({
						uniqueKey: '售后单表',
						methodName: 'acceptAfsApplyOrder'
					}, {}, {
						dealType,
						afsOrderId: v.afsOrderId
					}, '审核通过', true).then((res) => {
						if (dealType == '1' && !['2', '1'].includes(v.syncErpBreakageStatus)&&showConfigModal) {
							uni.navigateTo({
								url: `/pages/BcmViews/PickingOrder/breakage?afsOrderId=` + v.afsOrderId + '&type=2'
							});
						}
					})
				} else { }
			}
		});
	} else {
		orderAction({
			uniqueKey: '售后单表',
			methodName: 'acceptAfsApplyOrder'
		}, {}, {
			dealType,
			afsOrderId: v.afsOrderId
		}, '审核通过', true).then((res) => {
			if (dealType == '1' && !['2', '1'].includes(v.syncErpBreakageStatus)&&showConfigModal) {
				uni.navigateTo({
					url: `/pages/BcmViews/PickingOrder/breakage?afsOrderId=` + v.afsOrderId + '&type=2'
				});
			}
		})
	}
}

const getAll = async function (orderId: any, refundOperateType: any) {
	let list: any = [], params: any = {
		orderId,
		refundOperateType
	};
	const response: any = await bcmRequest(bcmUrl.orderApi, '订单表', 'PreCalculateRefund', params);
	if (!response.HasException) {
		if (response?.bcmOrderGoodsList?.length > 0 && response?.bcmOrder?.refundOperateType?.length !=
			0) {
			response?.bcmOrderGoodsList?.map((v: any) => {
				const {
					preRefundGoodsAmount,
					prePartRefundGoodsNum,
					preRefundGoodsActualWeights,
					preRefundGoodsActualWeight
				} = v.prePartReturnInfo;
				if (response?.bcmOrder?.refundOperateType.includes('2') && refundOperateType ==
					'2') {
					v.applyRefundWeight = [];
					v.applyRefundPrice = [];
					v.partRefundGoodsNum = prePartRefundGoodsNum
					v.refundGoodsActualWeights = preRefundGoodsActualWeights
					if (!!v.prePartReturnInfo) {
						v.totalPrice = preRefundGoodsAmount?.toFixed(2);
						v.goodPrice = (preRefundGoodsAmount / prePartRefundGoodsNum).toFixed(2);
						preRefundGoodsActualWeights?.sort((a: any, b: any) => a.rowNo - b.rowNo)?.map((a: any) => {
							v.applyRefundWeight.push({
								...a,
								value: null
							});
							v.applyRefundPrice.push(undefined);
						})
					}
					list.push(v)
				}

				if (response?.bcmOrder?.refundOperateType.includes('3') && refundOperateType ==
					'3') {
					if (!!v.prePartReturnInfo) {
						v.totalPrice = preRefundGoodsAmount?.toFixed(2);
						v.goodPrice = (preRefundGoodsAmount / prePartRefundGoodsNum).toFixed(2);
						v.refundsGoodsWeight = preRefundGoodsActualWeight;
						v.partRefundGoodsNum = prePartRefundGoodsNum;
					}
					list.push(v)
				}

				if (response?.bcmOrder?.refundOperateType.includes('1') && refundOperateType ==
					'1') {
					v.checked = false;
					v.applyRefundNum = 0;
					if (!!v.prePartReturnInfo) {
						v.totalPrice = preRefundGoodsAmount?.toFixed(2);
						v.goodPrice = (preRefundGoodsAmount / prePartRefundGoodsNum)?.toFixed(2);
						v.partRefundGoodsNum = prePartRefundGoodsNum;
					}
					list.push(v)
				}

				if (response?.bcmOrder?.refundOperateType.includes('6') && refundOperateType ==
					'6') {
					list.push(v)
				}
			})
		}

	} else {
		list = []
	}
	return list
}

const onSelect = function (item: any) {
	if (item.text === '部分退款' && item.value.refundOperateType.includes('1')) {
		getAll(item.value.orderId, ['1']).then((data: any) => {
			if (data.length != 0) {
				let partOptions = {
					goodsList: data,
					orderId: item.value.orderId,
					consigneeName: item.value.consigneeName,
					consigneePhoneLast: item.value.consigneePhoneLast,
					consigneePhone: item.value.privacyConsigneePhone,
					chnlType: item.value.chnlType
				};
				uni.setStorageSync('partOptions', JSON.stringify(partOptions));
				uni.navigateTo({
					url: `/pages/BcmViews/PickingOrder/partRefund?orderStatus=` + item.value.orderStatus + '&showModal=' + showConfigModal,
				});
			} else {
				uni.setStorageSync('partOptions', JSON.stringify({}));
				uni.showToast({
					duration: 3500,
					icon: 'none',
					title: `当前订单[${item.value.thirdOrderNo}]无可退商品`
				});
			}
		})
	}
	if (item.text === '重量退差' && item.value.refundOperateType.includes('2')) {
		getAll(item.value.orderId, ['2']).then((data: any) => {
			if (data.length != 0) {
				let partOptions = {
					goodsList: data,
					orderId: item.value.orderId,
					consigneeName: item.value.consigneeName,
					consigneePhoneLast: item.value.consigneePhoneLast,
					consigneePhone: item.value.privacyConsigneePhone,
					chnlType: item.value.chnlType
				};
				uni.setStorageSync('partOptions', JSON.stringify(partOptions));
				uni.navigateTo({
					url: `/pages/BcmViews/PickingOrder/weightRefund?orderStatus=` + item.value.orderStatus + '&showModal=' + showConfigModal,
				});
			} else {
				uni.setStorageSync('partOptions', JSON.stringify({}));
				uni.showToast({
					duration: 3500,
					icon: 'none',
					title: `当前订单[${item.value.thirdOrderNo}]无可退商品`
				});
			}
		})
	}

	if (item.text === '金额退差' && item.value.refundOperateType.includes('3')) {
		getAll(item.value.orderId, ['3']).then((data: any) => {
			if (data.length != 0) {
				let partOptions = {
					goodsList: data,
					orderId: item.value.orderId,
					consigneeName: item.value.consigneeName,
					consigneePhoneLast: item.value.consigneePhoneLast,
					consigneePhone: item.value.privacyConsigneePhone,
					chnlType: item.value.chnlType
				};
				uni.setStorageSync('partOptions', JSON.stringify(partOptions));
				uni.navigateTo({
					url: `/pages/BcmViews/PickingOrder/amountRefund?orderStatus=` + item.value.orderStatus + '&showModal=' + showConfigModal,
				});
			} else {
				uni.setStorageSync('partOptions', JSON.stringify({}));
				uni.showToast({
					duration: 3500,
					icon: 'none',
					title: `当前订单[${item.value.thirdOrderNo}]无可退商品`
				});
			}
		})

		return
	}

	if (item.text === '取消订单') {
		emit('update:modelValue', item.value)
		emit('update:modalType', item.value.orderStatus === '6' ? 'rejectOrderCancelApply' : 'cancel')
		emit('update:title', item.value.orderStatus === '6' ? '请选择拒绝退款申请原因' : '请选择取消订单原因')
		emit('update:isOrderCancel', true)
		emit('update:showCancelOrderPopup', true)
		return
	}
}
</script>
<style lang="scss" scoped>
.margin {
  margin: 0 15rpx !important;
}
</style>